import openpyxl
import os

def find_xlsx_file():
    """在当前目录中查找第一个xlsx文件"""
    for file in os.listdir("."):
        if file.endswith(".xlsx"):
            return file
    return None

def generate_error_code_from_xlsx(output_path="errorcode.h"):
    # 查找xlsx文件
    xlsx_file = find_xlsx_file()
    if not xlsx_file:
        print("当前目录下未找到 xlsx 文件！")
        return

    print(f"已找到文件：{xlsx_file}")
    workbook = openpyxl.load_workbook(xlsx_file)
    sheet = workbook.active  # 获取第一个工作表

    enum_entries = []
    map_entries = []

    # 遍历工作表的每一行，跳过表头
    for row in sheet.iter_rows(min_row=2, values_only=True):
        error_code_name, error_message = row
        if not error_code_name or not error_message:
            continue  # 忽略无效行

        # 转换为合法枚举名格式
        enum_name = error_code_name.strip()
        enum_entries.append(f"    {enum_name},")
        map_entries.append(f"        {{ErrorCode::{enum_name}, \"{error_message}\"}},")

    # 生成 C++ 代码
    code = f"""
#include <QString>
#include <unordered_map>

enum class ErrorCode {{
{chr(10).join(enum_entries)}
}};

inline QString GetErrorMessage(ErrorCode code) {{
    static const std::unordered_map<ErrorCode, QString> errorMessages = {{
{chr(10).join(map_entries)}
    }};

    auto it = errorMessages.find(code);
    if (it != errorMessages.end()) {{
        return it->second;
    }}
    return "未知错误";
}}
"""

    # 写入到输出文件
    with open(output_path, 'w', encoding='utf-8') as output_file:
        output_file.write(code)

    print(f"生成的 C++ 代码已保存到文件: {output_path}")

# 执行转换
generate_error_code_from_xlsx()
